package com.room.search.util;

import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.Properties;

/**
 * By   : ghd.bright
 * Time : 2021/8/30
 * Description: FastDFS工具类
 */

public class FastDfsUtils {

    FastDfsUtils() {
    }

    private static final Logger logger = LoggerFactory.getLogger(FastDfsUtils.class);

    static
    {
        try {
            Properties props = new Properties();
            props.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS,"101.33.238.3:22122");
            props.put(ClientGlobal.CONF_KEY_CONNECT_TIMEOUT, 2);
            props.put(ClientGlobal.CONF_KEY_NETWORK_TIMEOUT, 30);
            props.put(ClientGlobal.CONF_KEY_CHARSET, "UTF-8");
            props.put(ClientGlobal.CONF_KEY_HTTP_SECRET_KEY, "FastDFS123456789");
            props.put(ClientGlobal.PROP_KEY_HTTP_ANTI_STEAL_TOKEN, "no");
            props.put(ClientGlobal.PROP_KEY_CONNECTION_POOL_ENABLED, true);
            props.put(ClientGlobal.CONF_KEY_HTTP_TRACKER_HTTP_PORT, 22122);
            props.put(ClientGlobal.PROP_KEY_CONNECTION_POOL_MAX_COUNT_PER_ENTRY, 500);
            props.put(ClientGlobal.PROP_KEY_CONNECTION_POOL_MAX_IDLE_TIME, 3600);
            props.put(ClientGlobal.PROP_KEY_CONNECTION_POOL_MAX_WAIT_TIME_IN_MS, 1000);

            ClientGlobal.initByProperties(props);


            logger.info("初始化fastDFS成功");
        } catch (Exception e) {
            logger.error("初始化FastDfs失败-----{}",e.getMessage());
        }
    }

    /**
     * 生成trackerServer
     */

    private static TrackerServer trackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getTrackerServer();
    }


    /**
     * 生成 ----storageClient
     */
    private static StorageClient storageClient() throws IOException {
        TrackerServer trackerServer = trackerServer();
        return new StorageClient(trackerServer, null);
    }


    /***
     *  上传文件
     */
    public static String[] upload(MultipartFile file) {
//    获取文件名字
        String name = file.getOriginalFilename();
        if (name == null) {
            name = file.getName();
        }
        logger.info("文件名：{}", name);
//    获取storageClient
        StorageClient storageClient = null;
        String[] uploadFile = null;
        try {
            storageClient = storageClient();

//          上传
            uploadFile = storageClient.upload_file(file.getBytes(), name.substring(name.lastIndexOf(".")+1), null);
        } catch (Exception e) {
            logger.info("上传文件失败-----{}",e.getMessage());
        }
//      判断上传结果
        if (null != uploadFile) {
            logger.info("上传文件成功-----{}",storageClient.getErrorCode());
        }
        return uploadFile;
    }


    /**
     * 获取文件信息
     */
    public static FileInfo getFileinfo(String groupname, String remoteFilename) {
        StorageClient storageClient;
        try {
            storageClient = storageClient();
            return storageClient.get_file_info(groupname, remoteFilename);
        } catch (Exception e) {
            logger.error("获取文件信息失败----{}", e.getMessage());
        }
        return null;
    }


    /***
     * 下载文件
     */
    public static InputStream downloadFile(String groupName, String remoteFileName) {
        StorageClient storageClient;
        try {
            storageClient = storageClient();
            byte[] fileBytes = storageClient.download_file(groupName, remoteFileName);
            return new ByteArrayInputStream(fileBytes);
        } catch (Exception e) {
            logger.error("下载文件失败-----{}", e.getMessage());
        }
        return null;
    }


    /**
     * 删除文件
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = storageClient();
            storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            logger.error("下载删除失败失败-----{}", e.getMessage());
        }
    }

    /**
     * 获取文件路径
     */
    public static String getTrackerUrl() {

        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer;
        StorageServer storeStorage = null;
        try {
            trackerServer =  trackerClient.getTrackerServer();
            storeStorage =  trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            logger.error("获取文件路径失败-----{}", e.getMessage());

        }
        if (storeStorage == null) {
            return null;
        }
        return "http://" + storeStorage.getInetSocketAddress() + ":8888/";
    }

}



